package com.sjzs.web.interceptor;

import org.apache.struts2.interceptor.ScopeInterceptor;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.opensymphony.xwork2.ActionInvocation;

public class SpringTransactionInterceptor extends ScopeInterceptor {
	private static final long serialVersionUID = 5826344916155579352L;
	transient PlatformTransactionManager platformTM;
	transient ThreadLocal<TransactionStatus> myTransactionHolder = new ThreadLocal<TransactionStatus>();

	public void setPlatformTM(PlatformTransactionManager platformTM) {
		this.platformTM = platformTM;
	}

	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		TransactionStatus ts = getDefaultTransaction();
		try {
			return super.intercept(actionInvocation);
		} catch (Exception e) {
			if (!ts.isCompleted()) {
				platformTM.rollback(ts);
			}
			throw e;
		}
	}

	@Override
	public void beforeResult(ActionInvocation actionInvocation, String result) {
		super.beforeResult(actionInvocation, result);
		commitTransaction();
	}

	private TransactionStatus getDefaultTransaction() {
		TransactionStatus ts = platformTM.getTransaction(new DefaultTransactionDefinition());
		myTransactionHolder.set(ts);
		return ts;
	}

	private void commitTransaction() {
		TransactionStatus ts = myTransactionHolder.get();
		if (!ts.isCompleted()) {
			platformTM.commit(ts);
		}
	}
}
